


//编写代码, 基于 CountDownLatch 模拟跑步比赛的过程
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class Demo1 {

    //比赛开始的倒计时
    private static CountDownLatch countDownLatchStart = new CountDownLatch(1);
    //比赛结束的倒计时
    private static CountDownLatch countDownLatchEnd = new CountDownLatch(3);

    static class Runner implements Runnable {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "准备就绪");
            try {
                countDownLatchStart.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "开始跑步");
            try {
                //防止取出0
                int time = new Random().nextInt(3) + 1;
                TimeUnit.SECONDS.sleep(time);
                System.out.println(Thread.currentThread().getName() + "经过" + time + "秒后抵达终点");
                countDownLatchEnd.countDown();

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new Thread(new Runner(), "一号运动员").start();
        new Thread(new Runner(), "二号运动员").start();
        new Thread(new Runner(), "三号运动员").start();
        //给足时间让运动员准备
        TimeUnit.SECONDS.sleep(5);
        System.out.println("各就各位，GO!");
        //开跑
        countDownLatchStart.countDown();
        //等大家都到终点，就宣布比赛结束
        countDownLatchEnd.await();
        System.out.println("比赛结束");
    }
}
